# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging
from piHAlibs import (my_fctname,coroutine)
from .parsers import RFXCOMParsers

logger = logging.getLogger()

def item2msgs(item):
    if not item[1].startswith('0x') : return None
    namedev = item[0]
    if 'RFXCOM' not in namedev : return None
    sdata = item[1].split()
    hd = sdata[0]
    data = sdata[1:]
    logger.debug("Header %s",hd)
    model = 'NC'
    if hd in ('0x14','0x20','0x22','0x29'):
       	model = hd
    elif hd in ('0x38','0x40'):
        if (sdata[1] + sdata[2][2:] == '0x1a2d'):
       	    model ='0x1a2d'
        else:
       	    model = hd
    elif hd == '0x6c':
       	model = sdata[1]
    elif hd == '0x78':
        if (sdata[1] + sdata[2][2:] == '0xea7c'):
       	    model = '0xea7c'
        elif (sdata[1] + sdata[2][2:] == '0x1a2d'):
       	    model = '0x1a2d'
        elif sdata[1] == '0xea':
       	    model = '0x78ea'
    else:
        if int(hd,16) > 48: model = sdata[1] + sdata[2][2:]
    logger.debug("Model Id header %s",model)
    logger.debug("Data to decode %s",repr(data))
    p = [ int(i,16) for i in data ]
    logger.debug("Packet to decode %s",repr(p))
    return [namedev, hd, data, p, model, hd,item[1]]


@my_fctname
@coroutine
def RFXCOMparser(decoders,rejected=None):
    """
    item = [namedev,events]
    split events (if several) before sending to RFXCOMparser1
    """
    while True:
        events = (yield)
        logger.debug("Event receive %s",repr(events))
        evts = events[1].split('|')
        if len(evts) > 1:
            for event in evts:
                RFXCOMparser1(decoders,rejected=None).send([events[0],event])
        else:
            RFXCOMparser1(decoders,rejected=None).send(events)


@my_fctname
@coroutine
def RFXCOMparser1(decoders,rejected=None):
    """
    Parse header for RFXcom
    item = [namedev,event]
    Send to next target = decoder
    """
    hdps = RFXCOMParsers
    while True:
        item = (yield)
        logger.debug("Event receive %s",repr(item))
        #['RFX0:RFXCOM','0x44 0xea 0x4c 0x20 0x36 0x70 0x22 0x40 0x33 0x17']
        msgs = item2msgs(item)
        if not msgs : continue
        hdp = (msgs[5],msgs[4])
        if hdp not in hdps:
            if rejected: rejected.send(['NEW_PRORFX',hdp] + item)
            continue
        msgs[1] = hdps[hdp][0]		#protocol
        logger.debug("%s",repr(msgs))
        for target in decoders:
            logger.debug("Data sent to %s",repr(target))
            target.send(msgs)
